package top.wlink.bzgrowup;

import android.content.ContentValues;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import top.wlink.bzgrowup.bzex.SqliteHandlerx;

import static org.junit.Assert.assertEquals;
import static top.wlink.bzgrowup.bzex.Datex.date;
import static top.wlink.bzgrowup.bzex.Datex.datetime;
import static top.wlink.bzgrowup.bzex.Datex.getDayZeroTime;

/**
 * Instrumentation test, which will execute on an Android device.
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    private static final String TAG = "UTEST";

    @Test
    public void useAppContext() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();
        assertEquals("top.wlink.bzgrowup", appContext.getPackageName());
    }

    @Test
    public void TestLogical() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();
        SqliteHandlerx mySqlite = SqliteHandlerx.getInstance();
        if (mySqlite.createTable())
            Log.d(TAG, "test1, create table ok");
        else
            Log.d(TAG, "test1, create table failed!");

        List<String> las_insertSql = new ArrayList<>();
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('德', '日行一善', '每日', 0);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('智', '英数物化30分钟', '每日', 0);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('体', '步行30分钟', '每日', 0);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('美', '文学艺术30分', '每日', 0);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('劳', '扫洗擦整20分', '每日', 0);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('德', '还信用卡2', '每月', 12);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('德', '还信用卡1', '每月', 11);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('智', '总结计划', '每周', 1);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('智', '网易公开课', '长期', 0);");
        las_insertSql.add("insert into settings(kind, title, timer, tick) values('德', '克制就是美德，不和傻瓜辩论20170905', '长期', 0);");

        long ll_curMs = System.currentTimeMillis(); // - 2 * 86400000;
        long ll_lastMs = ll_curMs - ( 2 * 86400000 ); //  86400000是一天。 这里应该从系统里面取，没有就默认昨天.如果是当天。就运行1次。

        int li_day = (int) ( (  getDayZeroTime(ll_curMs) - getDayZeroTime(ll_lastMs) ) / 86400000.0 ) ;

        if (mySqlite.runSqlBatch(las_insertSql)){
            List<ContentValues> retVal = mySqlite.getSqlResult("select * from settings", null);
            StringBuilder sb = new StringBuilder("");
            for (ContentValues cv: retVal){
                // 每条记录；
                for (Map.Entry<String, Object> item : cv.valueSet()) {
                    sb.append( item.getKey() ).append(":").append(item.getValue().toString()).append(",");
                }
                sb.append(" \r\n ");

                final String ls_timer = cv.get("timer").toString();
                final int li_tick = Integer.parseInt(cv.get("tick").toString());
                final Integer li_setid = Integer.parseInt(cv.get("id").toString());

                Log.d(TAG, " --- " + ls_timer + " ==  " + li_tick);

                //mWay = String.valueOf(lc_today.get(Calendar.DAY_OF_WEEK));
                for (int iDay=1; iDay<=li_day; iDay++) {
                    Calendar lc_iday = Calendar.getInstance(Locale.CHINA);
                    lc_iday.setTimeInMillis(ll_lastMs + iDay * 86400000);

                    Log.d(TAG, " adding record for -- " + datetime.format(lc_iday.getTime()));

                    int li_weekday = lc_iday.get(Calendar.DAY_OF_WEEK) - 1;
                    if (li_weekday == 0) li_weekday = 7;  // 周天是7。
                    int li_monthday = lc_iday.get(Calendar.DAY_OF_MONTH);
                    String ls_daybegin = date.format( lc_iday.getTimeInMillis() );
                    String ls_dayend = date.format( lc_iday.getTimeInMillis() + 86400000 ); // 后一天

                    if ( ls_timer.equals("每日")
                            || (ls_timer.equals("长期"))
                            || ( ls_timer.equals("每周")  && li_tick==li_weekday)
                            || ( ls_timer.equals("每月")  && li_tick==li_monthday)  ){

                        Log.d(TAG, "get in for " +  ls_timer +" weekday "+li_weekday +  " md " +li_monthday);

                        List<ContentValues> l_count = mySqlite.getSqlResult(
                                "select count(*) as cc from records where pid=? and rectime>? and rectime<? ",
                                new String[]{ li_setid.toString(), ls_daybegin, ls_dayend } );
                        if (!l_count.isEmpty()){
                            if ( Integer.parseInt(l_count.get(0).get("cc").toString()) > 0 ) {
                                Log.d(TAG, "已经存在。");
                            }
                            else{  // 没有该数据，可以插入。
                                String ls_insrecord =
                                        "insert into records(pid,kind,timer,rectime,title,tasktime,timeout,status)" +
                                        "            values (?, ?,  ?, ?, ?, ? , ?, ? );";

                                String[] lsa_ins =  new String[]
                                        { li_setid.toString(),  cv.get("kind").toString(), ls_timer, datetime.format(lc_iday.getTime()),
                                        cv.get("title").toString(),  ls_daybegin, ls_dayend, "进行" };

                                if (ls_timer.equals("长期"))
                                    lsa_ins[4] = "9206-12-21 09:50";

                                mySqlite.runSql(ls_insrecord,lsa_ins);
                                Log.d(TAG, "插入！");
                            }
                        }
                    }
                }
            }
            Log.d(TAG, sb.toString() );
        }
        else Log.d(TAG, "插入运行失败");

        las_insertSql.clear();

        //getSqlResult
        List<ContentValues> retVal2 = mySqlite.getSqlResult("select * from records", null);
        StringBuilder sb2 = new StringBuilder("");
        for (ContentValues cv: retVal2) {
            // 每条记录；
            for (Map.Entry<String, Object> item : cv.valueSet()) {
                sb2.append(item.getKey()).append(":").append(  null != item.getValue()? item.getValue().toString():"").append(",");
            }
            sb2.append(" \r\n ");
        }
        Log.d(TAG, " ------ record： " + sb2.toString() );

        String ls_curTime = datetime.format(ll_curMs);
        Log.d(TAG, " ------ 当天 ： " + ls_curTime );
        //当天任务
        retVal2.clear();
        retVal2 = mySqlite.getSqlResult(
                "select * from records where ?>tasktime and ?<timeout order by status, kind ",
                new String[]{ ls_curTime, ls_curTime });
        sb2 = new StringBuilder("");
        for (ContentValues cv: retVal2) {
            // 每条记录；
            for (Map.Entry<String, Object> item : cv.valueSet()) {
                sb2.append(item.getKey()).append(":").append(  null != item.getValue()? item.getValue().toString():"").append(",");
            }
            sb2.append(" \r\n ");
        }
        Log.d(TAG, " ------ 当天任务 " + sb2.toString() );

        //过期任务
        retVal2 = mySqlite.getSqlResult(
                "select * from records where ?>timeout and status='进行' order by status, kind ",
                new String[]{ ls_curTime });
        sb2 = new StringBuilder("");
        for (ContentValues cv: retVal2) {
            // 每条记录；
            for (Map.Entry<String, Object> item : cv.valueSet()) {
                sb2.append(item.getKey()).append(":").append(  null != item.getValue()? item.getValue().toString():"").append(",");
            }
            sb2.append(" \r\n ");
        }
        Log.d(TAG, " ------ 过期任务 " + sb2.toString() );

        mySqlite.runSql("update records set status ='完成' where id in (1,3,4,7,8 ) ", null);

        //过往任务
        retVal2 = mySqlite.getSqlResult(
                "select * from records where status <>'进行' and timeout<=? order by status, kind ",
                new String[]{ date.format(getDayZeroTime(ll_curMs)) });
        sb2 = new StringBuilder("");
        for (ContentValues cv: retVal2) {
            // 每条记录；
            for (Map.Entry<String, Object> item : cv.valueSet()) {
                sb2.append(item.getKey()).append(":").append(  null != item.getValue()? item.getValue().toString():"").append(",");
            }
            sb2.append(" \r\n ");
        }
        Log.d(TAG, " ------ 过往已处理任务 " + sb2.toString() );

        Log.d(TAG, "" + R.string.hms_update_message_new);
                //hms_update_message_new
    }





}
